package com.common.utility;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.Drawable.ConstantState;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ImageView;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class ImageUtil {
	// private static String TAG = "ImageUtil";

	public static Bitmap getBitmapByStream(InputStream stream, int width, int height) {
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;// 设置为ture，只计算不加载到内存
		Bitmap bitmap = BitmapFactory.decodeStream(stream, null, options);
		int h = options.outHeight;// 原来的高度
		int w = options.outWidth;// 原来的宽度

		int beWidth = w / width; // 宽 缩放比
		int beHeight = h / height; // 高 缩放比

		int be = 1;
		if (beWidth < beHeight) {// 如果宽的缩放比比高的缩放比小
			be = beWidth;// 按照宽的缩放比
		} else {
			be = beHeight;
		}
		if (be <= 0) {
			be = 1;
		}
		options = new BitmapFactory.Options();
		options.inSampleSize = be;
		options.inJustDecodeBounds = false;// 设置为false
											// 重新加载bitmap，bitmap不为null
		bitmap = BitmapFactory.decodeStream(stream, null, options);

		return bitmap;
	}

	public static File getFileByUri(Uri uri, ContentResolver contentResolver) {
		String[] proj = { MediaStore.Images.Media.DATA };
		Cursor actualimagecursor = contentResolver.query(uri, proj, null, null, null);
		if(actualimagecursor == null){
			return null;
		}
		int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		actualimagecursor.moveToFirst();
		String img_path = actualimagecursor.getString(actual_image_column_index);
		File file = null;
		if(TextUtils.isEmpty(img_path)){
			Log.e("mark", "path:"+uri.getPath());
			return null;
		}else{
			
			try {
				file = new File(img_path);
			} catch (Exception e) {
				file = null;
				e.printStackTrace();
			}
		}
		
		
		return file;
	}

	/**
     * 将图片内容解析成字节数组
	 * @param
	 * @param inStream
	 * @return byte[]
	 * @throws Exception
	 */
	public static byte[] readStream(InputStream inStream) throws Exception {
		byte[] buffer = new byte[1024];
		int len = -1;
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		while ((len = inStream.read(buffer)) != -1) {
			outStream.write(buffer, 0, len);
		}
		byte[] data = outStream.toByteArray();
		outStream.close();
		inStream.close();
		return data;
	}

	public static long getByteSize(InputStream inStream) {
		byte[] buffer = new byte[1024];
		int len = -1;
		byte[] data = null;
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		try {
			while ((len = inStream.read(buffer)) != -1) {
				outStream.write(buffer, 0, len);
			}
			data = outStream.toByteArray();
			outStream.close();
			inStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return data == null ? 0 : data.length;
	}

	public static Drawable getDrawableByBytes(byte[] bytes, int width, int height) {
		Bitmap myBitmap = ImageUtil.getBitmapThumbnail(bytes, width, height);// 缩放图片
		Drawable bitmapDrawable = new BitmapDrawable(myBitmap);
		return bitmapDrawable;
	}

	public static Bitmap getBitmapByBytes(byte[] bytes, int width, int height) {
		return ImageUtil.getBitmapThumbnail(bytes, width, height);// 缩放图片
	}

	/**
     * 将字节数组转换为ImageView可调用的Bitmap对象
	 * @param
	 * @param bytes
	 * @param opts
	 * @return Bitmap
	 */
	public static Bitmap getPicFromBytes(byte[] bytes, BitmapFactory.Options opts) {
		if (bytes != null)
			if (opts != null)
				return BitmapFactory.decodeByteArray(bytes, 0, bytes.length, opts);
			else
				return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
		return null;
	}

	/**
     * 图片缩放
	 * @param
	 * @param bitmap
	 *            对象
	 * @param w
	 *            要缩放的宽度
	 * @param h
	 *            要缩放的高度
	 * @return newBmp 新 Bitmap对象
	 */
	public static Bitmap zoomBitmap(Bitmap bitmap, int w, int h) {
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		Matrix matrix = new Matrix();
		float scaleWidth = ((float) w / width);
		float scaleHeight = ((float) h / height);
		matrix.postScale(scaleWidth, scaleHeight);
		Bitmap newBmp = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
		return newBmp;
	}

	/**
	 * 把Bitmap转Byte
	 * 
	 * @Author zjc
	 * @EditTime 2010-07-19 上午11:45:56
	 */
	public static byte[] Bitmap2Bytes(Bitmap bm) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
		return baos.toByteArray();
	}

	/**
	 * 把字节数组保存为一个文件
	 * 
	 * @Author zjc
	 * @EditTime 2010-07-19 上午11:45:56
	 */
	public static File getFileFromBytes(byte[] b, String outputFile) {
		BufferedOutputStream stream = null;
		File file = null;
		try {
			file = new File(outputFile);
			FileOutputStream fstream = new FileOutputStream(file);
			stream = new BufferedOutputStream(fstream);
			stream.write(b);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (stream != null) {
				try {
					stream.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
		return file;
	}

	/**
	 * 把字节数组保存为一个文件
	 * 
	 * @param b
	 * @param dir
	 * @return
	 */
	public static final File getImageFileByByteArray(byte[] b, String dir) {
		String imagePath = dir + File.separator + System.currentTimeMillis()+".jpg";
		File file = null;
		BufferedOutputStream stream = null;
		try {
			file = new File(imagePath);
			FileOutputStream fstream = new FileOutputStream(file);
			stream = new BufferedOutputStream(fstream);
			stream.write(b);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (stream != null) {
				try {
					stream.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
		return file;

	}

	/**
	 * 
	 * 方法描述：将一个文件转成另外一个文件并保存
	 * 
	 * @param file
	 * @return
	 */
	public static File getFileByFile(File file, int maxWidth, int maxHeight,int quality) {
		Bitmap bitmap = getBitmapByFile(file, maxWidth, maxHeight);
		String path = file.getAbsolutePath().substring(0, file.getAbsolutePath().lastIndexOf("/"));
		File targetFile = saveBitmapToSDcard(path, bitmap, quality);
		return targetFile;
	}

	public static Bitmap getBitmapThumbnail(Bitmap src, int width, int height) {
		byte[] mContent = Bitmap2Bytes(src);
		return getBitmapThumbnail(mContent, width, height);
	}

	public static Bitmap getBitmapByFile(String filePath) {
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inSampleSize = 4;
		Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
		return bitmap;
	}

	public static Bitmap getBitmapThumbnail(byte[] mContent, int width, int height) {
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		// 获取图片的宽和高
		Bitmap bitmap = BitmapFactory.decodeByteArray(mContent, 0, mContent.length, options);

		int h = options.outHeight;// 原来的高度
		int w = options.outWidth;// 原来的宽度

		int beWidth = w / width; // 宽 缩放比
		int beHeight = h / height; // 高 缩放比
		int be = 1;
		if (beWidth < beHeight) {
			be = beWidth;
		} else {
			be = beHeight;
		}
		if (be <= 0) {
			be = 1;
		}
		options.inJustDecodeBounds = false;
		options.inSampleSize = be;
		options.outWidth = width;
		options.outHeight = height;
		options.inPreferredConfig = Config.ARGB_8888;
		options.inPurgeable = true;
		options.inInputShareable = true;
		// 重新读入图片，注意这次要把options.inJustDecodeBounds 设为 false哦
		bitmap = BitmapFactory.decodeByteArray(mContent, 0, mContent.length, options);
		// 利用ThumbnailUtils来创建缩略图，这里要指定要缩放哪个Bitmap对象
		bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);

		return bitmap;
	}

	/**
	 * 保持长宽比缩小Bitmap
	 * 
	 * @param bitmap
	 * @param maxWidth
	 * @param maxHeight
	 * @return
	 */
	public static Bitmap resizeBitmap(Bitmap bitmap, int maxWidth, int maxHeight) {
		int originWidth = bitmap.getWidth();
		int originHeight = bitmap.getHeight();

		// no need to resize
		if (originWidth < maxWidth && originHeight < maxHeight) {
			return bitmap;
		}

		int width = originWidth;
		int height = originHeight;

		// 若图片过宽, 则保持长宽比缩放图片
		if (originWidth > maxWidth) {
			width = maxWidth;

			double i = originWidth * 1.0 / maxWidth;
			height = (int) Math.floor(originHeight / i);
			// Bitmap 图片 缩放 成指定的尺寸
			bitmap = Bitmap.createScaledBitmap(bitmap, width, height, false);
		}

		// 若图片过长, 则从上端截取
		if (height > maxHeight) {
			height = maxHeight;
			// 剪切 图片, 只取图片的某个区域
			bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height);
		}
		return bitmap;
	}

	//
	public static File saveBitmapToSDcard(String path, Bitmap bitmap, int quality) {
		String imagePath = path + File.separator + System.currentTimeMillis()+".jpg";
		File file = null;
		FileOutputStream out = null;
		try {
			file = new File(imagePath);
			if (!file.exists()) {
				file.createNewFile();
			}
			out = new FileOutputStream(file);
			if (bitmap.compress(Bitmap.CompressFormat.JPEG, quality, out)) {
				out.flush();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
            if(bitmap != null){
                bitmap.recycle();
                bitmap = null;
            }
			if(out != null){
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return file;
	}

	/**
	 * 通过路径获取file对象
	 * 
	 * @param fileName
	 * @param path
	 * @return
	 */
	public static File getFileByPath(String fileName, String path) {
		String imagePath = path + fileName;
		File file = new File(imagePath);
		if (file.exists()) {
			return file;
		}
		return null;
	}

	// public static Bitmap getBitmapByFile(File file){
	// if(null==file)
	// return null;
	// String path = file.getPath();
	// Bitmap bmp = BitmapFactory.decodeFile(path);
	// return bmp;
	// }

	public static Bitmap getBitmapByByte(byte[] data, int width, int height) {
		Bitmap bitmap = null;
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;// 设置为ture，只计算不加载到内存
		bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);

		int h = options.outHeight;// 原来的高度
		int w = options.outWidth;// 原来的宽度

		int beWidth = w / width; // 宽 缩放比
		int beHeight = h / height; // 高 缩放比

		int be = 1;
		if (beWidth < beHeight) {// 如果宽的缩放比比高的缩放比小
			be = beWidth;// 按照宽的缩放比
		} else {
			be = beHeight;
		}
		if (be <= 0) {
			be = 1;
		}
		options.inSampleSize = be;
		options.inJustDecodeBounds = false;// 设置为false 重新加载bitmap，bitmap不为null
		bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);
		// 利用ThumbnailUtils来创建缩略图，这里要指定要缩放哪个Bitmap对象
		bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
		return bitmap;
	}

	public static Bitmap getBitmapByFile(File file, int width, int height) {
		Bitmap bitmap = null;
		if (file != null && file.exists()) {
			BitmapFactory.Options options = new BitmapFactory.Options();
			
			options.inJustDecodeBounds = true;// 设置为ture，只计算不加载到内存
			bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);// bitmap为null
			int h = options.outHeight;// 原来的高度
			int w = options.outWidth;// 原来的宽度

			Logger.e("---------------------------------------");
			Logger.e("h:" + h + ";w:" + w);
			Logger.e("---------------------------------------");
			int beWidth = w / width; // 宽 缩放比
			int beHeight = h / height; // 高 缩放比

			int be = 1;
			if (beWidth < beHeight) {// 如果宽的缩放比比高的缩放比小
				be = beWidth;// 按照宽的缩放比
			} else {
				be = beHeight;
			}
			if (be <= 0) {
				be = 1;
			}
			options.inSampleSize = be;
			options.inJustDecodeBounds = false;// 设置为false
												// 重新加载bitmap，bitmap不为null
			options.inTempStorage = new byte[5*1024*1024];
			bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
		}

		return bitmap;
	}

	public static Drawable getDrawableByFile(File file, int width, int height) {
		Bitmap bitmap = getBitmapByFile(file, width, height);
		return new BitmapDrawable(bitmap);
	}

	/**
	 * 此方法用于判断图片背景是否相等
	 * 
	 * @param ctx
	 * @param imageView
	 * @param resourceId
	 * @return
	 */
	public static boolean judgeImageBackground(Context ctx, ImageView imageView, int resourceId) {
		Drawable currentDrawable = imageView.getBackground();
		ConstantState currentConstantState = currentDrawable.getConstantState();
		// 资源id
		Drawable defaultDrawable = ctx.getResources().getDrawable(resourceId);
		ConstantState defaultConstantState = defaultDrawable.getConstantState();
		if (null != currentConstantState && null != defaultConstantState && currentConstantState.equals(defaultConstantState)) {
			return true;
		}
		return false;
	}
	
	public static Drawable changeGray(Context ctx,int resId){
		Drawable mDrawable = ctx.getResources().getDrawable(resId);  
		//Make this drawable mutable.  
		//A mutable drawable is guaranteed to not share its state with any other drawable.  
		mDrawable.mutate();  
		ColorMatrix cm = new ColorMatrix();  
		cm.setSaturation(0);  
		ColorMatrixColorFilter cf = new ColorMatrixColorFilter(cm);  
		mDrawable.setColorFilter(cf); 
		return mDrawable;
	}
	
	
	 /**
     * 转换图片成圆形
     * @param bitmap 传入Bitmap对象
     * @return
     */
    public static Bitmap toRoundBitmap(Bitmap bitmap) {
            int width = bitmap.getWidth();
            int height = bitmap.getHeight();
            float roundPx;
            float left,top,right,bottom,dst_left,dst_top,dst_right,dst_bottom;
            if (width <= height) {
                    roundPx = width / 2;
                    top = 0;
                    bottom = width;
                    left = 0;
                    right = width;
                    height = width;
                    dst_left = 0;
                    dst_top = 0;
                    dst_right = width;
                    dst_bottom = width;
            } else {
                    roundPx = height / 2;
                    float clip = (width - height) / 2;
                    left = clip;
                    right = width - clip;
                    top = 0;
                    bottom = height;
                    width = height;
                    dst_left = 0;
                    dst_top = 0;
                    dst_right = height;
                    dst_bottom = height;
            }
             
            Bitmap output = Bitmap.createBitmap(width,
                            height, Config.ARGB_8888);
            Canvas canvas = new Canvas(output);
             
            final int color = 0xff424242;
            final Paint paint = new Paint();
            final Rect src = new Rect((int)left, (int)top, (int)right, (int)bottom);
            final Rect dst = new Rect((int)dst_left, (int)dst_top, (int)dst_right, (int)dst_bottom);
            final RectF rectF = new RectF(dst);

            paint.setAntiAlias(true);
             
            canvas.drawARGB(0, 0, 0, 0);
            paint.setColor(color);
            canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

            paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
            canvas.drawBitmap(bitmap, src, dst, paint);
            return output;
    }
    
	/***
	 * 等比例压缩图片
	 * 
	 * @param bitmap
	 * @param screenWidth
	 * @param screenHight
	 * @return
	 */
	public static Bitmap getBitmap(Bitmap bitmap, int screenWidth,
			int screenHight) {
		int w = bitmap.getWidth();
		int h = bitmap.getHeight();
		Log.e("jj", "图片宽度" + w + ",screenWidth=" + screenWidth);
		Matrix matrix = new Matrix();
		float scale = (float) screenWidth / w;
		float scale2 = (float) screenHight / h;

		// scale = scale < scale2 ? scale : scale2;

		// 保证图片不变形.
		matrix.postScale(scale, scale);
		// w,h是原图的属性.
		return Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
	}

}
